package com.tanhua.dubbo.api;

import cn.hutool.core.util.PageUtil;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import javax.swing.*;
import java.util.List;

@DubboService
public class VideoApiImpl implements VideoApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    //上传视频
    public void save(Video video) {
        mongoTemplate.save(video);
    }

    //根据视频id，查询视频列表
    public List<Video> findByIds(String[] vids, Integer page, Integer pagesize) {
        //1.判断当前Redis中的数据。是否足以分页
        int redisPages = PageUtil.totalPage(vids.length, pagesize);//Redis中的总页数
        if (page <= redisPages) {
            //2.数据支持分页是查询Redis中的数据
            Criteria criteria = Criteria.where("id").in(vids);
            Query query = Query.query(criteria)
                    .skip((page - 1) * pagesize)
                    .limit(pagesize);
            return mongoTemplate.find(query, Video.class);
        } else {
            //2.当推荐数据不足以分页时，查询所有
            Integer currPage = page - redisPages;
            return findAll(currPage, pagesize);//查询总数，从第一页开始
        }

    }

    //分页查询所有视频列表（根据发布时间倒叙）
    public List<Video> findAll(Integer page, Integer pagesize) {
        Query query = new Query()
                .with(Sort.by(Sort.Order.desc("created")))
                .skip((page - 1) * pagesize)
                .limit(pagesize);
        return mongoTemplate.find(query,Video.class);
    }

    //分页查询用户视频列表
    public PageResult findVideos(Long userId, Integer page, Integer pagesize) {
        //1.设置查询条件
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria);
        //2.查询总数
        long count = mongoTemplate.count(query, Video.class);
        //3.设置分页
        query.with(Sort.by(Sort.Order.desc("crested")))
                .limit(pagesize)
                .skip((page - 1) * pagesize);
        //4.查询List集合
        List<Video> list = mongoTemplate.find(query, Video.class);
        //5.构造PageResult返回
        return new PageResult(page,pagesize,count,list);
    }
}
